import os
import sys
import re
import matplotlib.pyplot as plt
import seaborn as sns

# Usage: python analyze_feature_extraction_time.py /path/to/origin_logs /path/to/scope_logs

def extract_parsing_time(origin_log_path):
    """Extracts the Parsing time in seconds from the origin log file."""
    parsing_time = None
    with open(origin_log_path, 'r') as f:
        for line in f:
            match = re.search(r'🕑 Parsing: ([0-9.]+) seconds', line)
            if match:
                parsing_time = float(match.group(1))
                break
    return parsing_time

def extract_feature_time(scope_log_path):
    """Extracts the feature extraction time in ms from the scope log file."""
    feature_time = None
    with open(scope_log_path, 'r') as f:
        for line in f:
            match = re.search(r'🕒 feature extraction time: ([0-9.]+)ms', line)
            if match:
                feature_time = float(match.group(1))
                break
    return feature_time

def get_uuid_from_filename(filename):
    # Assumes format: <uuid>-<family>.<type>.log
    return filename.split('-')[0]

def main():
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} /path/to/origin_logs /path/to/scope_logs")
        sys.exit(1)
    origin_dir = sys.argv[1]
    scope_dir = sys.argv[2]

    # Map uuid to file path
    origin_logs = {get_uuid_from_filename(f): os.path.join(origin_dir, f)
                   for f in os.listdir(origin_dir) if f.endswith('.origin.log')}
    scope_logs = {get_uuid_from_filename(f): os.path.join(scope_dir, f)
                  for f in os.listdir(scope_dir) if f.endswith('.scope.log')}

    # Find uuids present in both
    common_uuids = set(origin_logs.keys()) & set(scope_logs.keys())

    total_times = []
    for uuid in common_uuids:
        parsing_time = extract_parsing_time(origin_logs[uuid])
        feature_time = extract_feature_time(scope_logs[uuid])
        if parsing_time is not None and feature_time is not None:
            total_time = parsing_time * 1000 + feature_time  # ms
            total_times.append(total_time)

    # Filter for cutoff at 4000ms
    total_times = [t for t in total_times if t <= 4000]

    if not total_times:
        print("No valid log pairs with both parsing and feature extraction times found.")
        sys.exit(1)

    # Plot histogram
    plt.figure(figsize=(10,6))
    sns.histplot(total_times, bins=100, kde=False, edgecolor='black')
    plt.xlabel('Total Feature Extraction Time (ms)')
    plt.ylabel('Number of Instances')
    plt.title('Histogram of Total Feature Extraction Time')
    plt.grid(True, linestyle='--', alpha=0.6)
    plt.tight_layout()
    plt.savefig('feature_extraction_time_histogram.png')
    plt.show()
    print(f"Histogram saved as feature_extraction_time_histogram.png")

if __name__ == '__main__':
    main() 